//
//  UserAccountViewModel.swift
//  SinaWeiBo20
//
//  Created by tarena on 16/3/22.
//  Copyright © 2016年 tarena. All rights reserved.
//

import UIKit

import AFNetworking


//viewModel 将一些业务逻辑 添加到这个类中 
class UserAccountViewModel: NSObject {
    
    static let sharedAccountViewModel: UserAccountViewModel = UserAccountViewModel()
    
    var account : UserAccount?
    
    //用户是否登录
    var userLogin: Bool {
        return account?.access_token != nil
    }
    
    var token : String? {
        return account?.access_token
    }
    
    var userName: String? {
        return account?.name
    }
    
    //用户头像URL
    var headURL: NSURL? {
        return NSURL(string: (account?.avatar_large ?? ""))
    }
    
    override init() {
        account = UserAccount.shareUserAccount()
    }
    
    
    func OAuthAccessToken(code:String, finished:(error : NSError?)->()){
        let AFManager = AFHTTPSessionManager()
        AFManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        let parameters = NSMutableDictionary()
        parameters.setValue(appid, forKey: "client_id")
        parameters.setValue(appSecret, forKey: "client_secret")
        parameters.setValue("authorization_code", forKey: "grant_type")
        parameters.setValue(code, forKey: "code")
        parameters.setValue(redirect_uri, forKey: "redirect_uri")
        
        AFManager.POST("https://api.weibo.com/oauth2/access_token", parameters: parameters, success: { (_ , returnData) -> Void in
            
            if let dict = returnData as? [String : AnyObject] {
                //                    print(dict)
                self.loadUserInfo(UserAccount(dict: dict),finished: finished)
            }
            
            }) { (_ , error ) -> Void in
                print("OAuth2_Access_Token_error:\(error.userInfo)")
        }
    }
    
    private func loadUserInfo(account : UserAccount, finished:(error : NSError?)->()){
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token":account.access_token!, "uid":account.uid!]
        let AFManager = AFHTTPSessionManager()
        AFManager.GET(urlString, parameters: parameters, success: { (_ , resultData) -> Void in
            if let dict = resultData as? [String : AnyObject] {
//                print(dict)
                account.name = dict["name"] as? String
                account.avatar_large = dict["avatar_large"] as? String
                account.saveAccount()
                finished(error: nil)
            }
            }) { (_ , error ) -> Void in
                finished(error: error)
        }
        
        
    }
    
    

}
